<template>
  <div class="property-management-container">
      <!-- 主内容区域 -->
      <main class="content">
        <!-- 页面标题 -->
        <div class="page-header">
          <h1>房产管理</h1>
          <el-button type="primary" @click="showAddPropertyDialog">
            <el-icon><Plus /></el-icon>
            新增房产
          </el-button>
        </div>

        <!-- 统计信息 -->
        <div class="stats-section">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-number">{{ totalProperties }}</div>
                <div class="stat-label">房产总数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-number">{{ availableProperties }}</div>
                <div class="stat-label">可租/售房产</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-number">{{ occupiedProperties }}</div>
                <div class="stat-label">已入住房产</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-number">{{ maintenanceProperties }}</div>
                <div class="stat-label">维修中房产</div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 搜索筛选区域 -->
        <div class="search-section">
          <el-card>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-input
                  v-model="searchQuery"
                  placeholder="搜索房产编号、地址、业主姓名"
                  clearable
                  @clear="handleSearch"
                  @keyup.enter="handleSearch"
                />
              </el-col>
              <el-col :span="4">
                <el-select v-model="buildingFilter" placeholder="选择楼栋" clearable @change="handleSearch">
                  <el-option
                    v-for="building in buildings"
                    :key="building"
                    :label="building"
                    :value="building"
                  />
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-select v-model="statusFilter" placeholder="选择状态" clearable @change="handleSearch">
                  <el-option
                    v-for="status in statusOptions"
                    :key="status.value"
                    :label="status.label"
                    :value="status.value"
                  />
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-button type="primary" @click="handleSearch">搜索</el-button>
                <el-button @click="resetFilters">重置</el-button>
              </el-col>
            </el-row>
          </el-card>
        </div>

        <!-- 房产列表 -->
        <div class="property-list-section">
          <el-card>
            <el-table :data="properties" style="width: 100%" height="450px" v-loading="loading">
              <el-table-column prop="propertyCode" label="房产编号" width="120" />
              <el-table-column prop="building" label="楼栋" width="100" />
              <el-table-column prop="room" label="房间号" width="100" />
              <el-table-column prop="typeId" label="房产类型" width="120" />
              <el-table-column prop="area" label="面积(m²)" width="100" />
              <el-table-column prop="structure" label="户型" width="100" />
              <el-table-column prop="owner" label="业主" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="getStatusType(scope.row.status)">
                    {{ getStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180" fixed="right">
                <template #default="scope">
                  <el-button type="primary" link @click="showEditPropertyDialog(scope.row)">编辑</el-button>
                  <el-button type="danger" link @click="confirmDeleteProperty(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </div>

        <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      </main>
  <!-- 新增/编辑房产对话框 -->
      <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
    >
      <el-form :model="formData" label-width="100px">
        <el-form-item label="楼栋">
          <el-input v-model="formData.building" placeholder="请输入楼栋号" />
        </el-form-item>
        <el-form-item label="房间号">
          <el-input v-model="formData.room" placeholder="请输入房间号" />
        </el-form-item>
        <el-form-item label="房产类型">
          <el-select v-model="formData.type" placeholder="请选择房产类型">
            <el-option label="住宅" value="residential" />
            <el-option label="商铺" value="commercial" />
            <el-option label="车位" value="parking" />
          </el-select>
        </el-form-item>
        <el-form-item label="面积">
          <el-input v-model.number="formData.area" placeholder="请输入面积(平方米)" type="number" />
        </el-form-item>
        <el-form-item label="户型">
          <el-select v-model="formData.structure" placeholder="请选择户型">
            <el-option label="一居室" value="1-bedroom" />
            <el-option label="两居室" value="2-bedroom" />
            <el-option label="三居室" value="3-bedroom" />
            <el-option label="四居室" value="4-bedroom" />
            <el-option label="商铺" value="shop" />
            <el-option label="车位" value="parking" />
          </el-select>
        </el-form-item>
        <el-form-item label="业主姓名">
          <el-input v-model="formData.owner" placeholder="请输入业主姓名" />
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="formData.contact" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="房产状态">
          <el-select v-model="formData.status" placeholder="请选择房产状态">
            <el-option label="可租/售" value="available" />
            <el-option label="已入住" value="occupied" />
            <el-option label="维修中" value="maintenance" />
            <el-option label="已售出" value="sold" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveProperty">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="400px"
    >
      <p>确定要删除该房产信息吗？此操作不可恢复。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteProperty">删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { propertyApi } from '../api/propertyApi'
import { ElMessage } from 'element-plus'
import type { Property, PropertyStats, SearchParams } from '@/types/property'

// 响应式数据
const currentPage = ref<number>(1)
const pageSize = ref<number>(10)
const searchQuery = ref<string>('')
const buildingFilter = ref<string>('')
const statusFilter = ref<string>('')
const dialogVisible = ref<boolean>(false)
const deleteDialogVisible = ref<boolean>(false)
const dialogTitle = ref<string>('新增房产')
const editingPropertyId = ref<string | null>(null)
const loading = ref<boolean>(false)

// 楼栋列表
const buildings = ref<string[]>([])

// 房产数据
const properties = ref<Property[]>([])
const totalCount = ref<number>(0)

// 统计信息
const stats = ref<PropertyStats>({
  totalProperties: 0,
  availableProperties: 0,
  occupiedProperties: 0,
  maintenanceProperties: 0
})

// 表单数据
const formData = ref<Omit<Property, 'id'>>({
  propertyCode: '',
  building: '',
  room: '',
  type: 'residential',
  area: 0,
  structure: '',
  owner: '',
  contact: '',
  status: 'available'
})

// 状态选项
const statusOptions = [
  { label: '可租/售', value: 'available' },
  { label: '已入住', value: 'occupied' },
  { label: '维修中', value: 'maintenance' },
  { label: '已售出', value: 'sold' }
]

// 计算属性
const totalProperties = computed<number>(() => stats.value.totalProperties)
const availableProperties = computed<number>(() => stats.value.availableProperties)
const occupiedProperties = computed<number>(() => stats.value.occupiedProperties)
const maintenanceProperties = computed<number>(() => stats.value.maintenanceProperties)







// 生命周期
onMounted(async (): Promise<void> => {
  await loadProperties()
})

// 方法

// 加载房产数据
const loadProperties = async (): Promise<void> => {
  loading.value = true
  try {
    const params: SearchParams = {
      propertyCode: searchQuery.value,
      building: buildingFilter.value,
      propertyStatus: statusFilter.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
    
    console.log('发送搜索分页查询请求到后端8081端口:', params)
    
    const response = await propertyApi.searchProperties(params)
    console.log('后端8081端口返回的搜索结果:', response)
    
    // 根据后端返回的数据结构进行调整
    console.log('后端返回的完整数据:', response)
    console.log('房产列表数据:', response.data?.list)
    
    // 确保数据是可迭代的数组
    properties.value = Array.isArray(response.data?.list) ? response.data.list : []
    totalCount.value = response.total || response.data?.list?.length || 0
    
    // 加载统计信息
    // const statsResponse = await propertyApi.getPropertyStats()
    // stats.value = statsResponse.data || stats.value
    
    // 加载楼栋列表
    const buildingsResponse = await propertyApi.getBuildings()
    buildings.value = buildingsResponse.data || []
    
  } catch (error) {
    console.error('加载房产数据失败:', error)
    ElMessage.error('加载房产数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = (): void => {
  currentPage.value = 1
  loadProperties()
}

// 重置筛选
const resetFilters = (): void => {
  searchQuery.value = ''
  buildingFilter.value = ''
  statusFilter.value = ''
  currentPage.value = 1
  loadProperties()
}

// 分页处理
const handleSizeChange = (size: number): void => {
  pageSize.value = size
  currentPage.value = 1
  loadProperties()
}

const handleCurrentChange = (page: number): void => {
  currentPage.value = page
  loadProperties()
}

const getStatusType = (status: string): string => {
  const typeMap: Record<string, string> = {
    available: 'success',
    occupied: 'info',
    maintenance: 'warning',
    sold: 'danger'
  }
  return typeMap[status] || 'default'
}

const getStatusText = (status: string): string => {
  const textMap: Record<string, string> = {
    available: '可租/售',
    occupied: '已入住',
    maintenance: '维修中',
    sold: '已售出'
  }
  return textMap[status] || '未知'
}

const showAddPropertyDialog = (): void => {
  dialogTitle.value = '新增房产'
  editingPropertyId.value = null
  formData.value = {
    building: '',
    room: '',
    type: 'residential',
    area: 0,
    structure: '',
    owner: '',
    contact: '',
    status: 'available'
  }
  dialogVisible.value = true
}

const showEditPropertyDialog = (property: Property): void => {
  dialogTitle.value = '编辑房产'
  editingPropertyId.value = property.id
  formData.value = { ...property }
  dialogVisible.value = true
}

const saveProperty = (): void => {
  if (editingPropertyId.value) {
    // 编辑现有房产
    const index = properties.value.findIndex(p => p.id === editingPropertyId.value)
    if (index !== -1) {
      properties.value[index] = { ...formData.value, id: editingPropertyId.value }
    }
  } else {
    // 添加新房产
    const newId = `P${new Date().getFullYear()}${String(properties.value.length + 1).padStart(3, '0')}`
    properties.value.push({
      ...formData.value,
      id: newId
    })
  }
  dialogVisible.value = false
}

const confirmDeleteProperty = (id: string): void => {
  editingPropertyId.value = id
  deleteDialogVisible.value = true
}

const deleteProperty = (): void => {
  const index = properties.value.findIndex(p => p.id === editingPropertyId.value)
  if (index !== -1) {
    properties.value.splice(index, 1)
  }
  deleteDialogVisible.value = false
}
</script>

<style scoped>
.property-management-container {
  width: 100%;
  background-color: #f5f7fa;
}

/* 内容区域样式 */
.content {
  padding: 20px;
}

/* 页面标题 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #303133;
  font-size: 24px;
}

/* 统计卡片样式 */
.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  text-align: center;
  transition: transform 0.3s, box-shadow 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

/* 搜索筛选区域 */
.search-section {
  margin-bottom: 20px;
}

/* 房产列表区域 */
.property-list-section {
  margin-bottom: 20px;
}

/* 分页区域 */
.pagination-section {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 对话框样式 */
.dialog-footer {
  text-align: right;
}
</style>